import { defineStore } from 'pinia';
import { DataStatus, Dictionary, UserSex } from '@/global';
import { reactive } from 'vue';

// 字典码表enum
export enum DictionaryMapEnum {
  sex = 'sex', // 性别
  dataStatus = 'dataStatus', // 数据状态
}

/**
 * 静态字典码表
 */
const staticDictionaryMakerMap: { key: DictionaryMapEnum, makeMethod: () => Dictionary[]}[] = [
  {
    key: DictionaryMapEnum.sex,
    makeMethod: (): Dictionary[] => [
      { text: '保密性别', value: UserSex.Inactivated },
      { text: '男', value: UserSex.Boy },
      { text: '女', value: UserSex.Girl }
    ]
  },
  {
    key: DictionaryMapEnum.dataStatus,
    makeMethod: (): Dictionary[] => [
      { text: '未激活', value: DataStatus.Inactivated },
      { text: '正常', value: DataStatus.Normal },
      { text: '已删除', value: DataStatus.Deleted }
    ]
  }
];

/**
 * 字典类状态
 */
class DictionariesState {
  private readonly _dictionaryMap: Map<DictionaryMapEnum, Dictionary[]>;
  constructor () {
    this._dictionaryMap = new Map<DictionaryMapEnum, Dictionary[]>();
  }

  get dictionaryMap (): Map<DictionaryMapEnum, Dictionary[]> {
    return this._dictionaryMap;
  }
}

export const useDictionariesStore = defineStore('dictionaries', () => {
  const dictionariesState = reactive(new DictionariesState());
  // 从字典列表里面取字典
  const getDictionary = (dictionaryEnum: DictionaryMapEnum) => dictionariesState.dictionaryMap.get(dictionaryEnum) ?? [];

  // 从接口中取字典或者把静态字典存进统一的map对象里
  const gainDictionary = (dictionaryEnum: DictionaryMapEnum) => {
    if (dictionariesState.dictionaryMap.get(dictionaryEnum)) {
      return dictionariesState.dictionaryMap.get(dictionaryEnum);
    } else {
      // 如果是静态字典码表，则从字典里面取
      const staticDictionary = staticDictionaryMakerMap.find(item => item.key === dictionaryEnum);
      if (staticDictionary) {
        dictionariesState.dictionaryMap.set(dictionaryEnum, staticDictionary.makeMethod());
      }
    }
  };
  return { dictionariesState, getDictionary, gainDictionary };
});
